package com.moyv.schoolbbs.base.chat.server;

import com.moyv.schoolbbs.bean.model.User;
import com.moyv.schoolbbs.ui.service.OnConversationListener;
import com.moyv.schoolbbs.ui.service.OnProgressListener;

import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.chat2.Chat;
import org.jivesoftware.smack.chat2.ChatManager;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smackx.offline.OfflineMessageManager;
import org.jxmpp.jid.EntityBareJid;
import org.jxmpp.jid.impl.JidCreate;
import org.jxmpp.stringprep.XmppStringprepException;

import java.io.Serializable;
import java.util.List;

public class MessagesServer implements Serializable {

    private ChatManager chatManager;

    private OnProgressListener onProgressListener;//用于交互的回调接口

    private OnConversationListener onConversationListener;//用于会话的接收消息回调
    private String id;

    //初始化
    public void init(AbstractXMPPConnection connection, OnProgressListener onProgressListener) {
        chatManager = ChatManager.getInstanceFor(connection);
        this.onProgressListener = onProgressListener;
        getOfflineMessage(connection);
        managerListener();
    }

    //离线消息
    private void getOfflineMessage(AbstractXMPPConnection connection) {
        try {
            OfflineMessageManager offlineMessageManager = new OfflineMessageManager(connection);
            List<Message> messageList = offlineMessageManager.getMessages();
            for (Message message : messageList) {
                mesListener(message);
            }
            offlineMessageManager.deleteMessages();//通知服务器删除离线消息，否则下次还在
            System.out.println("离线消息接收成功，共" + messageList.size() + "条。");
            System.out.println(messageList);
        } catch (Exception e) {
            System.out.println("离线消息接收错误！！！");
            e.printStackTrace();
        }finally {
            try {
                connection.sendStanza(new Presence(Presence.Type.available));//上线
            } catch (SmackException.NotConnectedException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void mesListener(Message message) {
        System.out.println(message.getFrom().getLocalpartOrThrow() + "-" + message.getType() + ":" + message.getBody());
        if (message.getBody()==null) return;
//        System.out.println(onConversationListener == null);
        if (onProgressListener != null) {
            onProgressListener.onProgress(message);
        }
        if (onConversationListener != null && message.getFrom().toString().startsWith(id))
            onConversationListener.ConversationMessageListener(message.getFrom().getLocalpartOrNull().toString(), message.getBody());
    }

    //消息监听
    private void managerListener() {
        //接受消息监听
        chatManager.addIncomingListener((from, message, chat) -> {
            mesListener(message);
        });
        //发送消息监听
        chatManager.addOutgoingListener((to, message, chat) -> {

        });
    }


    //一次性消息
    public boolean sendMessage(String mes, String to) {
        try {
            EntityBareJid jid = JidCreate.entityBareFrom(to);
            Chat chat = chatManager.chatWith(jid);
            Message message = new Message();
            if (chat != null) {
                message.setBody(mes);
                chat.send(message);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    //创建并获得一个会话
    public Conversation createConversation(String id, OnConversationListener onConversationListener) {
        this.onConversationListener = onConversationListener;
        this.id=id;
        return new Conversation(chatManager, id);
    }

    //会话
    public class Conversation {

        private ChatManager chatManager;
        private Chat chat;

        private User user;
        private String id;
        private EntityBareJid jid;

        private OnConversationListener onConversationListener;

        public Conversation(ChatManager chatManager, String id) {
            try {
                this.id = id;
                System.out.println("id:"+id);
                jid = JidCreate.entityBareFrom(id);
            } catch (Exception e) {
                e.printStackTrace();
            }
            this.chatManager = chatManager;
            chat = chatManager.chatWith(jid);
        }

        public void sendMessage(String mes) {
            try {
                chat.send(mes);
            } catch (SmackException.NotConnectedException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}